<template>
  <div class="list">
    <div class="item" v-for="(item,index) in list" :key="index">
      <el-time-picker is-range v-model="item.selected" :value-format="valueFormat" range-separator="至" :start-placeholder="startPlaceholder" :end-placeholder="endPlaceholder" placeholder="选择时间范围" @change="onChange"></el-time-picker>
        <el-button class="btn" v-if="index==0" type="primary" icon="el-icon-circle-plus-outline" size="mini" circle @click="add"></el-button>
        <el-button class="btn" v-else type="danger" icon="el-icon-delete" size="mini" circle @click="del(index)"></el-button>
    </div>
  </div>
</template>
<script>
export default {
    props: {
      value: {
        type: String,
        default: null
      },
      valueFormat: {
        type: String,
        default: 'HH:mm:ss'
      },
      startPlaceholder: {
        type: String,
        default: '开始'
      },
      endPlaceholder: {
        type: String,
        default: '结束'
      }
    },
    watch: {
        value: {
            handler(nv) {
                if(nv) {
                    const list = JSON.parse(nv);
                    this.list = list.map(item => {
                        return {selected: [item.startTime, item.endTime]}
                    })
                }
            },
            immediate: true,
        }
    },
    data() {
        return {
            list: [{}]
        }
    },
    methods: {
        onChange(e) {
            // console.log(e)
            // console.log(this.list)
            const arr = []
            this.list.forEach(item => {
                if(item.selected) {
                    const [sTime, eTime] = item.selected;
                    const obj = {};
                    obj.startTime = sTime;
                    obj.endTime = eTime;
                    arr.push(obj)
                }
            })

            // console.log(arr)
            this.$emit('input', arr && arr.length ? JSON.stringify(arr): null)
        },
        add() {
            this.list.push({})
            this.onChange()
        },
        del(index) {
            this.list.splice(index, 1)
            this.onChange()
        }
    }
}
</script>
<style lang="scss" scoped>
.list {
    border: 1px dashed #ccc;
    padding: 10px;
    border-radius: 10px;
    position: relative;
    .item+.item {
        margin-top: 10px;
    }
    .btn {
        margin-left: 10px;
    }
}
</style>